package com.xiejun.netty;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 用于连接PipelineServer的客户端
 */
public class PipelineClient {
    
    public static void main(String[] args) {
        try {
            ChannelHandler handler = new ClientHandler();
            new EnhancedSimpleNettyClient("localhost", 8082, handler).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 客户端处理器实现
     */
    static class ClientHandler implements ChannelHandler {
        
        @Override
        public void channelRead(SocketChannel channel, ByteBuffer buffer) throws IOException {
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);
            String message = new String(data);
            System.out.println("Received from server: " + message);
        }
        
        @Override
        public void channelConnected(SocketChannel channel) throws IOException {
            System.out.println("Connected to pipeline server: " + channel.getRemoteAddress());
        }
        
        @Override
        public void channelDisconnected(SocketChannel channel) throws IOException {
            System.out.println("Disconnected from pipeline server: " + channel.getRemoteAddress());
        }
    }
}